package com.hewep.demo.device.mina.core.codec;

import com.hewep.demo.device.mina.core.Request;
import com.hewep.demo.device.mina.core.message.BasicRequest;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;


public class DeviceDecoder extends CumulativeProtocolDecoder {
	
	private static final Logger log = LoggerFactory.getLogger(DeviceDecoder.class);
	
	private int bytesToInt(byte[] bytes) {
		int s = bytes[1] & 0xFF;
        System.out.println(s);
        s |= (bytes[0] << 8);
        s &= 0XFFFF;
        return s;
    }
	
	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,	ProtocolDecoderOutput out) throws Exception {
		if(in.remaining()<4){
			return false;
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		int spliteCount = 0;
		boolean msgOk = false;	
		while(in.hasRemaining()){			
			byte b= in.get();			
			int  s = (byte)b & 0xFF;
			baos.write(b);						
			if(s == 0xff){
				spliteCount++;
			}else{
				spliteCount = 0;
			}
			if(spliteCount == 2){
				msgOk = true;
				break;
			}
		}
		
		if(msgOk){	

			Request request = new BasicRequest();
//			request.setData(data);
			request.parseData();  // 解析数据
			out.write(request);
			return true;
		}
		return false;
	}
}
